package com.ruoyi.zxjd.common;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.zxjd.common.domain.CommonUserVO;
import com.ruoyi.zxjd.conference.domain.ConferenceArrange;
import com.ruoyi.zxjd.conference.service.IConferenceArrangeService;
import com.ruoyi.zxjd.document.domain.DocumentFile;
import com.ruoyi.zxjd.document.service.IDocumentFileService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 工作安排Controller
 *
 * @author lcc
 * @date 2021-01-22
 */
@Controller
@RequestMapping("/common")
public class ZxjdCommonController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ZxjdCommonController.class);
    private String prefix = "/common";

    @Autowired
    private ICommonService commonService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IDocumentFileService documentFileService;

    @Autowired
    private IConferenceArrangeService conferenceArrangeService;

    /**
     * 查询有效用户数
     */
    //@RequiresPermissions("active:user:count")
    @PostMapping("/activeUserCount")
    @ResponseBody
    public AjaxResult activeUserCount() {
        int count = commonService.countActiveUser();
        return AjaxResult.success(count);
    }

    /**
     * 查询有效用户
     */
    //@RequiresPermissions("active:user:list")
    @PostMapping("/activeUserList")
    @ResponseBody
    public AjaxResult activeUserList(CommonUserVO userVO) {
        List<CommonUserVO> users = commonService.listActiveUser(userVO);
        return AjaxResult.success(users);
    }

    @RequiresPermissions("common:choose:user")
    @GetMapping("/chooseUser")
    public String chooseUser(ModelMap mmap) {
        SysDept sysDept = new SysDept();
        sysDept.setStatus(UserConstants.NORMAL);
        sysDept.setDelFlag(UserConstants.NORMAL);
        List<SysDept> depts = sysDeptService.selectDeptList(sysDept);
        mmap.put("depts", depts);
        SysRole sysRole = new SysRole();
        sysRole.setStatus(UserConstants.NORMAL);
        sysRole.setDelFlag(UserConstants.NORMAL);
        List<SysRole> roles = sysRoleService.selectRoleList(sysRole);
        mmap.put("roles", roles);
        return prefix + "/choose_user";
    }

    @RequiresPermissions("common:choose:user")
    @GetMapping("/chooseUser1")
    public String chooseUser1(Long arrangeId, ModelMap mmap) {
        SysDept sysDept = new SysDept();
        sysDept.setStatus(UserConstants.NORMAL);
        sysDept.setDelFlag(UserConstants.NORMAL);
        List<SysDept> depts = sysDeptService.selectDeptList(sysDept);
        mmap.put("depts", depts);
        SysRole sysRole = new SysRole();
        sysRole.setStatus(UserConstants.NORMAL);
        sysRole.setDelFlag(UserConstants.NORMAL);
        List<SysRole> roles = sysRoleService.selectRoleList(sysRole);
        mmap.put("roles", roles);
        mmap.put("arrangeId", arrangeId);
        return prefix + "/choose_user1";
    }

    /**
     * 过滤查询有效用户
     */
    //@RequiresPermissions("active:user:list")
    @PostMapping("/activeUserList1")
    @ResponseBody
    public AjaxResult activeUserList1(CommonUserVO userVO) {
        ConferenceArrange conferenceArrange = conferenceArrangeService.selectConferenceArrangeById(userVO.getArrangeId());
        List<CommonUserVO> users = commonService.listActiveUser(userVO);
        String releaseScope = conferenceArrange.getReleaseScope();
        String[] s = releaseScope.split(" ");
        for (int i = 0; i < users.size(); i++) {
            for (int j = 0; j < s.length; j++) {
                if (users.get(i).getUserName().equals(s[j])) {
                    users.remove(i);
                }
            }
        }
        return AjaxResult.success(users);
    }

    /**
     * 文件上传
     */

    //@RequiresPermissions("common:file:upload")
    @Log(title = "附件上传", businessType = BusinessType.INSERT)
    @PostMapping("/file/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            DocumentFile documentFile = documentFileService.uploadFile(file);
            return AjaxResult.success(documentFile.getFileId());
        } catch (Exception e) {
            log.error("文件上传失败", e);
            //TODO 有bug,如果上传失败, 前端没有提示
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 文件下载
     */

    //@RequiresPermissions("common:file:download")
    @RequestMapping("/file/download")
    public void downloadFile(Long fileId, String fullfilename, HttpServletResponse response) {
        DocumentFile fileInfo = documentFileService.selectDocumentFileById(fileId);
        String fileName = fullfilename;
        if (StringUtils.isEmpty(fileName)) {
            fileName = fileInfo.getFileName();
        }
        ;
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFilePath = RuoYiConfig.getFileRealPath(fileInfo.getFilePath());
            response.setContentType(MediaType.APPLICATION_PDF_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(realFilePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 根据文件Id获取文件名称
     */
    @PostMapping("/file/fileInfo")
    @ResponseBody
    public AjaxResult fileInfo(Long fileId) {
        DocumentFile fileInfo = documentFileService.selectDocumentFileById(fileId);
        return AjaxResult.success(fileInfo);
    }

    /**
     * 根据文件Id获取文件路径
     */
    @GetMapping("/file/fileView/{fileId}")
    public String fileView(@PathVariable("fileId") Long fileId) {
        DocumentFile fileInfo = documentFileService.selectDocumentFileById(fileId);
        return fileInfo.getFilePath();
    }

    /**
     * 根据文件Id删除文件
     */
    //@RequiresPermissions("common:file:remove")
    @Log(title = "附件删除", businessType = BusinessType.DELETE)
    @PostMapping("/file/delOneFile")
    @ResponseBody
    public AjaxResult delOneFile(Long key) {
        DocumentFile fileInfo = documentFileService.selectDocumentFileById(key);
        String filePath = fileInfo.getFilePath();
        boolean bool = FileUtils.deleteFile(RuoYiConfig.getFileRealPath(filePath));
        if (bool) {
            documentFileService.deleteDocumentFileById(key);
        }
        return AjaxResult.success();
    }

}
